接收post请求(vue+axios)解决跨域问题(三)

您所在的位置:网站首页 axios vue 跨域 接收post请求(vue+axios)解决跨域问题(三)

接收post请求(vue+axios)解决跨域问题(三)

#接收post请求(vue+axios)解决跨域问题(三)| 来源: 网络整理| 查看: 265

编写接口连接并查询数据库数据(二)

1.通过postman测试post请求

新建一个接收post的路由

//根据post的id查询 var selId='select * from list where id=?' //响应post router.post('/list', function(req, res, next) { var id=req.body.id; //通过req的body拿到post的id pool.getConnection(function(err,suc){ suc.query(selId,[id],function(err,result){ if(result){ //数据库有返回数据 result={ //返回数据与格式 code:200, msg:'获取单个测试列表成功', data:result } } res.json(result); //响应返回json数据 suc.release(); //关闭数据库连接 }) }) });测试结果

id为1的数据

id为2的数据

2.Vue(axios发送post请求)

安装axios&element-ui

cnpm install axios --save //是一个基于 promise 的 HTTP 库 cnpm install element-ui --save //饿了么前端出品的一套 Vue.js 后台组件库

打开main.js引入

//element import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) //axios import axios from 'axios' axios.defaults.baseURL='http://localhost:3000'; //设置一个类似base_url的请求路径 global.axios=axios; //设置一个全局axios便于调用

打开helloword.vue

//html部分 //script部分 data(){ return{userList:[]} //用于接收返回数据 }, mounted(){ this.get() }, methods:{ get(){ var this_=this; //调用最开始写的那个接口,拉取全部数据 axios.post('/users/list',{id:1}).then(function(res){ this_.userList=res.data.data }).catch(function(err){ console.log(err) }) }, }

测试是否成功连接: 打开mysql 运行node服务 npm start 运行vue npm run dev 发现并没有拿到数据,查看控制台报错信息

报错信息

node服务运行在localhost:3000端口,vue运行在localhost:8080端口 解决方法是在node中配置cors解决不同端口的跨域问题 安装cors

cnpm install cors --save

在app.js中引入cors并配置

//cors var cors=require('cors'); app.use(cors({ origin:['http://localhost:8080'], //指定接收的地址 methods:['GET','POST'], //指定接收的请求类型 alloweHeaders:['Content-Type','Authorization'] //指定header }))

配置完成后重启node服务 打开vue,看到数据已经成功拿到

获取指定数据成功

对数据进行一些基本操作(四)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3